#include "AppDelegate.h"
#import <Flutter/Flutter.h>
#import <VeTOSiOSSDK/VeTOSiOSSDK.h>



@interface AppDelegate()

@property(nonatomic,strong)FlutterMethodChannel* uploadChannel;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [GeneratedPluginRegistrant registerWithRegistry:self];
    // Override point for customization after application launch.
    [self diposeFultterMethodFunction];
    
  
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}





#pragma mark ========== 处理Flutter相关的调用方法 =============

-(void)diposeFultterMethodFunction
{
    FlutterViewController* flutterViewController = (FlutterViewController *)[self topViewController];
 

      FlutterMethodChannel* sdkChannel = [FlutterMethodChannel
                                              methodChannelWithName:@"initTOSSDK"
                                              binaryMessenger:(NSObject<FlutterBinaryMessenger>*)flutterViewController];
    FlutterMethodChannel* uploadChannel = [FlutterMethodChannel
                                            methodChannelWithName:@"uploadMedia"
                                            binaryMessenger:(NSObject<FlutterBinaryMessenger>*)flutterViewController];
    self.uploadChannel=uploadChannel;
    __weak typeof(self) weakSelf =self;
    [sdkChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
        NSArray* callDic=call.arguments;
        if ([call.method isEqualToString:@"uploadImg"]) {
            [weakSelf uploadFile:callDic];
        }
     }];
    

}

//获取当前最上面的ViewController
- (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:self.window.rootViewController];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    
    return resultVC;
}

- (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
}


-(void)uploadFile:(NSArray*)arr{
    NSString* endpoint = @"tos-cn-beijing.volces.com";
    NSString*  region = @"cn-beijing";
    NSString*  filePath = arr.firstObject;
    NSString*  accessKey = arr[1];
    NSString*  secretKey = arr[2];
    NSString*  secretToken = arr[3];
    NSString*  type = arr.lastObject;
    TOSCredential *credential = [[TOSCredential alloc] initWithAccessKey:accessKey secretKey:secretKey securityToken:secretToken];
    TOSEndpoint *tosEndpoint = [[TOSEndpoint alloc] initWithURLString:endpoint withRegion:region];
    TOSClientConfiguration *config = [[TOSClientConfiguration alloc] initWithEndpoint:tosEndpoint credential:credential];
    TOSClient *client = [[TOSClient alloc] initWithConfiguration:config];

    TOSPutObjectFromFileInput *put = [TOSPutObjectFromFileInput new];
    put.tosBucket = @"pixverse-internal-upload";
    // 对象名，模拟 example_dir 下的 example_object.txt 文件
    NSString*fileName =filePath.lastPathComponent;
    NSString* objectKey =[NSString stringWithFormat:@"platform/%@/upload/%@",type,fileName] ;
    put.tosKey = objectKey;
    put.tosMeta = @{@"usermeta-key-1" : @"usermeta-value-1", @"usermeta-key-2" : @"usermeta-value-2"};
    put.tosFilePath =filePath;
    TOSTask *task = [client putObjectFromFile:put];
    [task continueWithBlock:^id(TOSTask *task) {
        if (!task.error) {
            TOSPutObjectFromFileOutput *output = task.result;
            if (output.tosETag.length>1) {
                NSLog(@"Put object from file tosETag: %@" ,output.tosETag);
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.uploadChannel invokeMethod:@"upload_media_file" arguments:output.tosETag];
                });
              
            }
        } else {
            NSLog(@"Put object from file failed, error: %@" ,task.error);
        }
        return nil;
    }];
}






@end
